/*
 * $Id: ProjectTreePane.java 25 2008-12-14 13:29:28Z rdubisz $
 * Created on 25 styczeń 2008, 20:30
 */
package wdp.project;

import java.awt.EventQueue;
import java.util.Iterator;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import wdp.entities.raw.Project;

/**
 *
 * @author  Robson
 */
public class ProjectTreePane extends javax.swing.JPanel {

    /** Creates new form ProjectTreePane */
    public ProjectTreePane() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    entityManager = javax.persistence.Persistence.createEntityManagerFactory("db.fdbPU").createEntityManager();
    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(wdp.WdpApp.class).getContext().getResourceMap(ProjectTreePane.class);
    query = entityManager.createQuery(resourceMap.getString("query.query")); // NOI18N
    list = org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
    jScrollPaneProjectTree = new javax.swing.JScrollPane();
    jTreeProjects = new javax.swing.JTree();
    initTree();

    setName("Form"); // NOI18N

    jScrollPaneProjectTree.setName("jScrollPaneProjectTree"); // NOI18N

    jTreeProjects.setName("jTreeProjects"); // NOI18N
    jTreeProjects.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
      public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
        jTreeProjectsValueChanged(evt);
      }
    });
    jScrollPaneProjectTree.setViewportView(jTreeProjects);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPaneProjectTree, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPaneProjectTree, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
    );
  }// </editor-fold>//GEN-END:initComponents

  private void jTreeProjectsValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeProjectsValueChanged
      Project oldSelected = selected;
      Object selectedObject = ((DefaultMutableTreeNode) evt.getPath().getLastPathComponent()).getUserObject();
      if(selectedObject instanceof Project ) {
        selected = (Project) selectedObject;
        log.fine("Zaznaczono: " + evt.getPath() + " / zmiana:" + oldSelected + " na " + selected);
        firePropertyChange("selected", oldSelected, selected);
      }
  }//GEN-LAST:event_jTreeProjectsValueChanged
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.persistence.EntityManager entityManager;
  private javax.swing.JScrollPane jScrollPaneProjectTree;
  private javax.swing.JTree jTreeProjects;
  private java.util.List<wdp.entities.ready.Project> list;
  private javax.persistence.Query query;
  // End of variables declaration//GEN-END:variables
    private DefaultMutableTreeNode top = new DefaultMutableTreeNode("Projects");
    private Project selected = null;
    private static Logger log = Logger.getLogger(ProjectTreePane.class.getName());

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new ProjectTreePane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    private void initTree() {
        getJTreeProjects().setModel(new DefaultTreeModel(top));
        getJTreeProjects().setExpandsSelectedPaths(true);
        getJTreeProjects().setSelectionPath((new TreePath(top)));
        //jTreeProjects.setRootVisible(false);
        readTree();
    }

    private void readSubTree(DefaultMutableTreeNode node, Project prj) {
        //System.out.println("SubTree: "+prj );
        query = entityManager.createQuery("SELECT p FROM Project p where p.idParrent.id=" + prj.getId()); // NOI18N

        list = org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        //System.out.println("Lista:"+list.size());
        for (Iterator it = list.iterator(); it.hasNext();) {
            Project project = (Project) it.next();
            DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(project);
            readSubTree(projectNode, project);
            node.add(projectNode);
        }
    }

    private void readTree() {
        query = entityManager.createQuery("SELECT p FROM Project p where p.idParrent IS NULL"); // NOI18N

        list = org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        //System.out.println("Lista:"+list.size());
        for (Iterator it = list.iterator(); it.hasNext();) {
            Project project = (Project) it.next();
            DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(project);
            readSubTree(projectNode, project);
            top.add(projectNode);
        }
    }

    public Project getSelected() {
        return selected;
    }

    public void setSelected(Project selected) {
        this.selected = selected;
    }

    public javax.swing.JTree getJTreeProjects() {
        return jTreeProjects;
    }
}
